<template>
  <div class="goods-add-drawer">
    <el-drawer v-model="drawerAddGoods" size="900" @close="closeGood" destroy-on-close="true">
      <template #header>
        <h4>添加商品</h4>
      </template>
      <template #default>
        <el-form
          label-position="top"
          label-width="auto"
          :model="goodsInfo"
          style="max-width: 600px"
          :rules="rulesGoods"
          ref="goodsForm">
          <el-form-item label="商品名" prop="name">
            <el-input v-model="goodsInfo.name" />
          </el-form-item>
          <el-form-item label="商品图片">
            <el-upload
              :disabled="isUploadBefore"
              class="avatar-uploader"
              :show-file-list="false"
              :on-change="handleFileSuccess"
              :auto-upload="false"
              drag="true">
              <img v-if="imgUrl" :src="imgUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品价格">
            <el-input v-model="goodsInfo.price" />
          </el-form-item>
          <el-form-item label="商品分类" prop="tag">
            <el-input v-model="goodsInfo.tag" />
          </el-form-item>
          <el-form-item label="商品描述" prop="descInfo">
            <el-input v-model="goodsInfo.descInfo" />
          </el-form-item>
          <el-form-item label="商品数量">
            <el-input-number v-model="goodsInfo.sum" :min="1" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="closeGood">取消</el-button>
          <el-button type="primary" @click="addGoods" v-if="addOrUpdateInfo">添加</el-button>
          <el-button type="primary" @click="updateGoods" v-else>更新</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { addGoodsInfo, getGoodsInfo, updateGoodsInfo } from '@/api/goods'
import { ElMessage } from 'element-plus'

const route = useRoute()

const emit = defineEmits(['addSuccess', 'updateSuccess'])

// 抽屉显示
const drawerAddGoods = ref(false)

// 添加/更新
const addOrUpdateInfo = ref(true)

// 表单对象
const goodsForm = ref()

const regexGoods = {
  nameRegex: /^[^\r\n]{1,15}$/,
  descRegex: /^[^\r\n]{1,30}$/,
  moneyRegex: /^\d+$/,
  tagRegex:
    /^(?:([\u4e00-\u9fa5\w]{1,14})(?:、([\u4e00-\u9fa5\w]{1,13}))*|([\u4e00-\u9fa5\w]{1,15}))$/
}

// 表单校验规则
const rulesGoods = {
  name: [
    { required: true, message: '请输入商品名', trigger: 'blur' },
    {
      pattern: regexGoods.nameRegex,
      message: '不能超过15个字符',
      trigger: 'blur'
    }
  ],
  descInfo: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    {
      pattern: regexGoods.descRegex,
      message: '不能超过30个字符',
      trigger: 'blur'
    }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    {
      pattern: regexGoods.moneyRegex,
      message: '请输入合法的数字格式',
      trigger: 'blur'
    }
  ],
  tag: [
    { required: true, message: '请输入分类', trigger: 'blur' },
    {
      pattern: regexGoods.tagRegex,
      message: '不能超过15个字符，且分割符只能用、',
      trigger: 'blur'
    }
  ]
}

// 商品数据
const goodsInfo = ref({
  name: '',
  image: '', // 图片文件
  price: '',
  descInfo: '',
  sum: 1
})

// 取消
const closeGood = () => {
  drawerAddGoods.value = false
  goodsInfo.value = {
    name: '',
    photos: '',
    price: '',
    tag: '',
    descInfo: '',
    sum: 1
  }
  imgUrl.value = ''
}

// 图片url
const imgUrl = ref()

// 成功上传文件
const handleFileSuccess = (value) => {
  imgUrl.value = URL.createObjectURL(value.raw)
  goodsInfo.value.photos = value.raw
}

// 限定图片只能添加时修改
const isUploadBefore = ref(false)

// 记录商品id
const goodsIdInfo = ref()

// 打开抽屉
const open = async (goodsId) => {
  goodsIdInfo.value = goodsId
  addOrUpdateInfo.value = drawerAddGoods.value = true
  if (goodsId) {
    isUploadBefore.value = true
    const res = (await getGoodsInfo(goodsId)).data
    if (res.code == 505) {
      ElMessage.error(res.msg)
      return
    }
    addOrUpdateInfo.value = false
    // 数据回显
    const info = res.data
    goodsInfo.value = {
      name: info.name,
      photos: info.photos,
      price: info.price,
      tag: info.tag,
      descInfo: info.descInfo,
      sum: info.sum
    }
    imgUrl.value = info.photos
  }
}

// 添加物品
const addGoods = async () => {
  await goodsForm.value.validate()
  const form = new FormData()
  for (let key in goodsInfo.value) {
    form.append(key, goodsInfo.value[key])
  }
  // 获取图片的url
  const res = (await addGoodsInfo(form, route.params.id)).data
  drawerAddGoods.value = false
  emit('addSuccess')
  closeGood()
}

// 更新物品信息
const updateGoods = async () => {
  await goodsForm.value.validate()
  const res = (await updateGoodsInfo(goodsInfo.value, goodsIdInfo.value)).data
  if (res.code == 504) {
    ElMessage.error('更新信息失败')
    return
  }
  drawerAddGoods.value = false
  emit('updateSuccess')
  closeGood()
}

defineExpose({
  open
})
</script>

<style scoped lang="scss">
.addGoods {
  height: 600px;
  background-color: white;
}

/* 布局 */
.el-container {
  padding: 5px;
}

/* 按钮位置 */
.goods-position {
  margin: 5px 10px 5px 0px;
}

/* 图片上传 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 264px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
